package com.ruoyi.appapi.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.system.domain.ZsyyUser;
import com.ruoyi.system.dto.SendMsgEntity;
import com.ruoyi.system.mapper.ZsyyUserMapper;
import com.ruoyi.system.wxService.MessageUtil;
import com.ruoyi.system.wxService.WxChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api/wechat")
@Api(value = "WxChatController", tags = "WeChat --> 微信模板消息推送")
public class WxChatController {
	@Autowired
	private WxChatService wxChatService;
	@Autowired
	private ZsyyUserMapper zsyyUserMapper;

	/**
	 * 我的openId:  oop8d5tXtEJfIE9I1K_hvvHCd1Oo
	 * @return
	 */
	@RequestMapping(value = "/sendTest", method = RequestMethod.GET)
	@ApiOperation("推送测试信息")
	public AjaxResult sendTest() {
		//给管理员推送设备状态信息
		SendMsgEntity entity1 = new SendMsgEntity();
		entity1.setFirstData("尊敬的管理员,您好！您有门禁设备掉线：");
		entity1.setKeyword1("开州大厦一单元前门") ;
		entity1.setKeyword2("F00122010");
		entity1.setKeyword3("已掉线");
		entity1.setKeyword4(CommonUtil.dateToStr(new Date()));
		entity1.setKeyword5("网络离线");
		entity1.setRemark("请尽快排查或安排技术人员进行设备维护！");
		wxChatService.sendDeviceMsg(entity1);
		return AjaxResult.success();
	}

	/**
	 * 获取所有用户的openid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAccountOpenIds", method = RequestMethod.GET)
	@ApiOperation("获取所有用户的openid")
	public AjaxResult getAccountOpenIds() {
		String[] result = null;
		try {
			result=wxChatService.getAccountOpenIds();
		}catch (Exception e){
			e.printStackTrace();
		}
		return AjaxResult.success(result);
	}
	/**
	 * token校验
	 * @param request
	 * @param response
	 */
	@PostMapping( "/checkToken")
	@ApiOperation("用户与公众号交互事件处理")
	public String  checkToken(HttpServletRequest request, HttpServletResponse response){
		//token验证代码段
		try{
			log.info("----------------开始处理微信发过来的消息------------------");
			// 微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
			request.setCharacterEncoding("UTF-8");
			// 在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
			response.setCharacterEncoding("UTF-8");
//			String respXml = CoreService.processRequest(request);
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 关注公众号进行openID处理
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					String unionid = wxChatService.getAccountUser(fromUserName);
					if (!CommonUtil.isEmpty(unionid)){
						ZsyyUser zsyyUser = zsyyUserMapper.getUserByUnionid(unionid);
						if (!CommonUtil.isEmpty(zsyyUser)){
							zsyyUser.setPublicOpenid(fromUserName);
							zsyyUserMapper.updateById(zsyyUser);
						}
					}
				}
			}
			log.info("----------返回微信消息处理结果-----------------------:处理成功！");
		}catch (Exception e){
			log.error("校验出错");
			e.printStackTrace();
		}
		return "ok";
	}

}

